<script lang="ts" setup>
import { computed } from 'vue';
import { NTag, NTooltip } from 'naive-ui';
import { $t } from '@/locales';

defineOptions({ name: 'MediaNfoInfo' });

interface Props {
  // nfo?: Api.Media.MediaNfo;
  nfo?: Api.Media.NfoDto;
  mode?: 'grid' | 'list';
  /** 是否显示评分等级提示 */
  showRatingTip?: boolean;
  /** 是否显示更多提示 */
  showMoreTip?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'grid',
  showRatingTip: true,
  showMoreTip: true
});

// 评分相关计算
const ratingLevel = computed(() => {
  const rating = props.nfo?.rating || 0;
  if (rating >= 9)
    return {
      level: 'excellent',
      color: '#18a058',
      text: $t('common.rating.excellent')
    };
  if (rating >= 7)
    return { level: 'good', color: '#f0a020', text: $t('common.rating.good') };
  if (rating >= 5)
    return { level: 'fair', color: '#f0a020', text: $t('common.rating.fair') };
  return { level: 'poor', color: '#d03050', text: $t('common.rating.poor') };
});

// 格式化时长
const formattedRuntime = computed(() => {
  const runtime = props.nfo?.runtime || 0;
  if (!runtime) return '';

  const hours = Math.floor(runtime / 60);
  const minutes = runtime % 60;

  const parts = [];
  if (hours > 0) parts.push(`${hours}${$t('common.hour')}`);
  if (minutes > 0 || !hours) parts.push(`${minutes}${$t('common.minute')}`);
  return parts.join(' ');
});

// 格式化发布日期
const formattedReleaseDate = computed(() => {
  if (!props.nfo?.releaseDate) return '';
  const date = new Date(props.nfo.releaseDate);
  if (props.mode === 'list') {
    return `${date.getFullYear()}-${formatNumber(
      date.getMonth() + 1
    )}-${formatNumber(date.getDate())}`;
  }
  return date.getFullYear().toString();
});

// 修改内容显示相关计算
const displayContent = computed(() => {
  const isListMode = props.mode === 'list';
  const actors = (props.nfo?.actors || [])
    .filter((actor) => actor && (actor.name || typeof actor === 'string'))
    .map((actor) => actor.name || actor);
  const directors = (props.nfo?.directors || [])
    .filter(
      (director) => director && (director.name || typeof director === 'string')
    )
    .map((director) => director.name || director);

  return {
    actors: actors.slice(0, isListMode ? 6 : 2),
    directors: directors.slice(0, isListMode ? 3 : 1),
    genres: (props.nfo?.genres || [])
      .filter(Boolean)
      .slice(0, isListMode ? 8 : 3),
    plot: props.nfo?.plot?.trim() || '',
    plotFormatted: isListMode
      ? props.nfo?.plot?.trim() || ''
      : (props.nfo?.plot?.trim() || '').slice(0, 100) +
      ((props.nfo?.plot?.length || 0) > 100 ? '...' : '')
  };
});

// 显示更多指示器计算
const moreIndicator = computed(() => {
  const nfo = props.nfo;
  if (!nfo) return { actors: 0, directors: 0, genres: 0 };
  const content = displayContent.value;

  // 过滤掉无效数据后再计算
  const actors = (nfo.actors || []).filter(
    (actor) => actor && (actor.name || typeof actor === 'string')
  ).length;
  const directors = (nfo.directors || []).filter(
    (director) => director && (director.name || typeof director === 'string')
  ).length;
  const genres = (nfo.genres || []).filter(Boolean).length;

  return {
    actors: Math.max(0, actors - content.actors.length),
    directors: Math.max(0, directors - content.directors.length),
    genres: Math.max(0, genres - content.genres.length)
  };
});

// 添加工具函数
const formatNumber = (num: number) => {
  return num < 10 ? `0${num}` : num.toString();
};
</script>

<template>
  <div
    :class="[
      mode,
      { empty: !nfo },
      { 'with-rating-tip': showRatingTip },
      { 'with-more-tip': showMoreTip },
    ]"
    class="nfo-info"
  >
    <template v-if="nfo">
      <!-- 评分和元数据行 -->
      <div class="meta-row">
        <div v-if="nfo.rating" :class="ratingLevel.level" class="rating">
          <NTooltip v-if="showRatingTip" placement="top" trigger="hover">
            <template #trigger>
              <div class="rating-content">
                <icon-material-symbols:star-rounded class="text-16px" />
                <span>{{ nfo.rating.toFixed(1) }}</span>
              </div>
            </template>
            <div class="tooltip-rating">
              <span class="rating-text">{{ ratingLevel.text }}</span>
              <span class="rating-value">{{ nfo.rating.toFixed(1) }}</span>
            </div>
          </NTooltip>
          <div v-else class="rating-content">
            <icon-material-symbols:star-rounded class="text-16px" />
            <span>{{ nfo.rating.toFixed(1) }}</span>
          </div>
        </div>
        <template v-if="formattedReleaseDate || formattedRuntime">
          <div v-if="nfo.rating" class="meta-divider">•</div>
          <div v-if="formattedReleaseDate" class="year">
            {{ formattedReleaseDate }}
          </div>
          <div
            v-if="formattedReleaseDate && formattedRuntime"
            class="meta-divider"
          >
            •
          </div>
          <div v-if="formattedRuntime" class="runtime">
            {{ formattedRuntime }}
          </div>
        </template>
      </div>

      <!-- 类型标签 -->
      <div
        v-if="displayContent.genres.length"
        :class="{ 'list-genres': mode === 'list' }"
        class="genres"
      >
        <TransitionGroup class="genres-container" name="tag-list" tag="div">
          <NTag
            v-for="genre in displayContent.genres"
            :key="genre"
            :bordered="false"
            :color="{
              color: 'rgba(var(--primary-color), 0.1)',
              textColor: 'rgb(var(--primary-color))',
            }"
            class="genre-tag"
            size="small"
          >
            <span class="genre-text">{{ genre }}</span>
          </NTag>
          <NTooltip
            v-if="moreIndicator.genres > 0"
            :key="'more'"
            placement="top"
          >
            <template #trigger>
              <NTag :bordered="false" class="genre-tag more-tag" size="small">
                <span class="more-count">+{{ moreIndicator.genres }}</span>
              </NTag>
            </template>
            <div class="tooltip-genres">
              {{ nfo.genres!.slice(displayContent.genres.length).join(' • ') }}
            </div>
          </NTooltip>
        </TransitionGroup>
      </div>

      <!-- 列表模式信息 -->
      <template v-if="mode === 'list'">
        <div class="list-info">
          <div class="list-content">
            <div class="meta-info">
              <div class="credits-container">
                <TransitionGroup name="fade">
                  <template
                    v-for="(type, key) in {
                      directors: 'director',
                      actors: 'actor',
                    }"
                    :key="key"
                  >
                    <div v-if="displayContent[key].length" class="credit-item">
                      <span class="label">{{ $t(`common.${type}`) }}:</span>
                      <div class="credit-content">
                        <NTooltip v-if="moreIndicator[key] > 0" placement="top">
                          <template #trigger>
                            <span class="credit-text">
                              {{ displayContent[key].join(', ') }}
                              <span class="more-indicator"
                              >+{{ moreIndicator[key] }}</span
                              >
                            </span>
                          </template>
                          <div class="tooltip-credits">
                            {{
                              (nfo[key] || [])
                                .filter(
                                  (item) =>
                                    item &&
                                    (item.name || typeof item === 'string')
                                )
                                .map((item) => item.name || item)
                                .join(', ')
                            }}
                          </div>
                        </NTooltip>
                        <span v-else class="credit-text">
                          {{ displayContent[key].join(', ') }}
                        </span>
                      </div>
                    </div>
                  </template>
                </TransitionGroup>
              </div>
            </div>

            <div v-if="displayContent.plot" class="plot-section">
              <NTooltip
                v-if="displayContent.plot.length > 200"
                :width="400"
                placement="top"
                trigger="hover"
              >
                <template #trigger>
                  <div class="plot with-tooltip">
                    <span class="plot-text">{{
                        displayContent.plotFormatted
                      }}</span>
                    <span
                      v-if="displayContent.plot.length > 100"
                      class="more-text"
                    >
                      {{ $t('common.more') }}
                    </span>
                  </div>
                </template>
                <div class="tooltip-plot">{{ displayContent.plot }}</div>
              </NTooltip>
              <div v-else class="plot">
                <span class="plot-text">{{ displayContent.plot }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>

<style scoped>
/* 基础布局 */
.nfo-info {
  display: flex;
  flex-direction: column;
  gap: 1px;
  width: 100%;
}

/* 评分和元数据样式 */
.meta-row {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.rating {
  display: flex;
  align-items: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.rating-content {
  display: flex;
  align-items: center;
  gap: 2px;
  font-weight: 600;
  font-size: 14px;
  padding: 2px 6px;
  cursor: help;
}

.rating.excellent {
  background-color: rgba(24, 160, 88, 0.1);
  color: #18a058;
}

.rating.good {
  background-color: rgba(240, 160, 32, 0.1);
  color: #f0a020;
}

.rating.poor {
  background-color: rgba(208, 48, 80, 0.1);
  color: #d03050;
}

.meta-divider {
  color: var(--n-text-color-3);
  font-size: 12px;
  line-height: 1;
}

.year,
.runtime {
  color: var(--n-text-color-3);
  font-size: 12px;
}

/* 类型标签样式 */
.genres {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin: 4px 0;
}

.genre-tag {
  transition: all 0.3s ease;
  max-width: 120px;
}

.genre-text {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

.more-count {
  display: inline-block;
  line-height: 1;
}

.genre-tag:hover {
  transform: translateY(-2px);
}

.more-tag {
  background-color: rgba(var(--primary-color), 0.05) !important;
  color: var(--n-text-color-3) !important;
}

/* 列表模式布局 */
.list-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.list-content {
  display: grid;
  grid-template-columns: minmax(180px, 1fr) minmax(0, 2.5fr);
  gap: 16px;
  align-items: start;
  width: 100%;
}

/* 演职人员信息样式 */
.meta-info {
  min-width: 0;
}

.credits-container {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.credit-item {
  display: flex;
  align-items: baseline;
  gap: 8px;
  font-size: 12px;
  line-height: 1.6;
}

.credit-content {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: baseline;
}

.credit-text {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.label {
  color: var(--n-text-color-3);
  margin-right: 4px;
}

.more-indicator {
  color: var(--n-text-color-3);
  font-size: 12px;
  margin-left: 4px;
}

/* 简介部分样式 */
.plot-section {
  position: relative;
  width: 100%;
}

.plot {
  position: relative;
  font-size: 12px;
  line-height: 1.6;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  word-break: break-word;
}

.plot-text {
  word-wrap: break-word;
}

.plot.with-tooltip {
  cursor: pointer;
}

.plot.with-tooltip:hover .more-text {
  text-decoration: underline;
}

.more-text {
  color: var(--n-primary-color);
  font-size: 12px;
  margin-left: 4px;
  opacity: 0.8;
}

.tooltip-plot {
  font-size: 12px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
}

/* 模式特定样式 */
.grid {
  min-height: 64px;
}

.list {
  min-height: 100px;
}

.list-genres {
  margin: 4px 0;
}

/* 空态样式 */
.empty {
  opacity: 0.5;
  min-height: 40px;
}

/* 动画效果 */
.tag-list-enter-active,
.tag-list-leave-active,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.tag-list-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.tag-list-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(10px);
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .list-content {
    grid-template-columns: minmax(180px, 1fr) minmax(0, 2fr);
    gap: 20px;
  }
}

@media (max-width: 960px) {
  .list-content {
    grid-template-columns: minmax(160px, 1fr) minmax(0, 1.8fr);
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .list-content {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .credits-container {
    gap: 8px;
  }

  .credit-item {
    flex-direction: column;
    gap: 4px;
  }

  .label {
    margin-right: 0;
  }

  .plot {
    -webkit-line-clamp: 4;
  }
}

@media (max-width: 480px) {
  .genres {
    gap: 4px;
  }

  .genre-tag {
    max-width: 80px;
    font-size: 11px;
  }

  .plot {
    -webkit-line-clamp: 3;
  }

  .credit-text {
    font-size: 11px;
  }
}

/* 暗色模式适配 */
:deep(.dark) {
  .rating.excellent {
    background-color: rgba(24, 160, 88, 0.2);
  }

  .rating.good {
    background-color: rgba(240, 160, 32, 0.2);
  }

  .rating.poor {
    background-color: rgba(208, 48, 80, 0.2);
  }

  .credit-text,
  .plot {
    color: var(--n-text-color-2);
  }

  .more-tag {
    background-color: rgba(255, 255, 255, 0.1) !important;
  }

  .meta-divider,
  .more-indicator {
    color: var(--n-text-color-3);
  }

  .rating-content {
    background-color: rgba(0, 0, 0, 0.2);
  }

  .genre-tag:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }
}

:deep(.n-tag) {
  line-height: 1.4;
}

/* 优化 tooltip 样式 */
.tooltip-credits,
.tooltip-genres,
.tooltip-plot {
  font-size: 12px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.tooltip-credits {
  max-width: 400px;
}

/* 优化标签布局 */
.genres-container {
  display: flex;
  flex-wrap: wrap;
  gap: inherit;
  width: 100%;
}

/* 优化评分提示样式 */
.tooltip-rating {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
}

.rating-text {
  font-size: 13px;
  font-weight: 500;
}

.rating-value {
  font-size: 12px;
  opacity: 0.8;
}

/* 优化评分样式 */
.rating.fair {
  background-color: rgba(240, 160, 32, 0.1);
  color: #f0a020;
}

/* 优化动画效果 */
.rating,
.genre-tag,
.credit-text {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.rating:hover,
.genre-tag:hover {
  transform: translateY(-2px);
  filter: brightness(1.1);
}

/* 优化暗色模式 */
:deep(.dark) {
  .rating.fair {
    background-color: rgba(240, 160, 32, 0.2);
  }

  .tooltip-rating {
    background-color: rgba(0, 0, 0, 0.2);
  }

  .rating:hover,
  .genre-tag:hover {
    filter: brightness(1.2);
  }
}

/* 优化响应式布局 */
@media (hover: hover) {
  .rating:hover,
  .genre-tag:hover {
    transform: translateY(-2px);
  }
}

@media (hover: none) {
  .rating:active,
  .genre-tag:active {
    transform: translateY(-1px);
  }
}
</style>
